import {Component, OnInit, ViewChild} from '@angular/core';
import {Business} from '../business';
import {BusinessService} from '../business.service';
import {ActivatedRoute} from '@angular/router';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {Location} from '@angular/common';
import {MyimguploadComponent} from '@shared/myimgupload/myimgupload.component';

@Component({
    selector: 'app-add',
    templateUrl: './add.component.html',
})
export class AddComponent implements OnInit {

    data: Business = {};
    bussinessForm: FormGroup;

    @ViewChild('imgload') myuploadimg: MyimguploadComponent;

    constructor(
        private bussinessService: BusinessService,
        private activeRouter: ActivatedRoute,
        private fb: FormBuilder,
        private location: Location,
    ) {
    }

    ngOnInit() {
        this.bussinessForm = this.fb.group({
            title: ['', Validators.required],
            url: ['', Validators.required],
            img: ['', Validators.required],
        });
        const id = this.activeRouter.snapshot.paramMap.get('id');

        if (id) {
            this.bussinessService.showBusiness(+id).subscribe(res => {
                this.data = res;

                this.bussinessForm.patchValue({
                    title: this.data.title,
                    url: this.data.url,
                    img: this.data.icon,
                });
                this.myuploadimg.setImg(this.data.icon);
            });
        }
    }

    uploadimg($event) {
        this.bussinessForm.patchValue({
            img: $event,
        });
    }


    save() {

        const  value = this.bussinessForm.value;
        this.data.icon = value['img'];
        this.data.url = value['url'];
        this.data.title = value['title'];
        this.bussinessService.updateBusiness(this.data).subscribe(res => {
            this.location.back();
        }, __ => {

        });
    }

}
